<template>
  <div class="adminSet">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-button
        @click="goback()"
        size="mini"
        type="primary"
        style="    position: absolute;
    right: 6px;
    top: 6px;"
        >返回</el-button
      >
      <el-form-item label="账号：" prop="userName">
        <el-input
          v-model="ruleForm.userName"
          :disabled="disabledFlag"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名：" prop="realName">
        <el-input v-model="ruleForm.realName"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-radio v-model="ruleForm.sex" :label="1">男</el-radio>
        <el-radio v-model="ruleForm.sex" :label="2">女</el-radio>
      </el-form-item>
      <el-form-item
        label="密码："
        prop="password"
        v-if="this.$route.params.flagmi"
      >
        <el-input v-model="ruleForm.password" type="password"></el-input>
      </el-form-item>
      <!-- <el-form-item label="邮箱：" prop="email">
        <el-input v-model="ruleForm.email" :disabled="disabledFlag"></el-input>
      </el-form-item> -->
      <el-form-item label="手机：" prop="tel">
        <el-input v-model="ruleForm.tel" :disabled="disabledFlag"></el-input>
      </el-form-item>
      <el-form-item label="选择组织：" prop="dangorgname">
        <el-input
          type="textarea"
          v-model="ruleForm.dangorgname"
          :readonly="true"
          :disabled="disabledFlag"
          style="width:300px"
        ></el-input>
        <el-button
          type="primary"
          @click="selectorg('ruleForm')"
          size="mini"
          v-if="flag3"
          >选择组织</el-button
        >
        <!-- <el-button @click="goback('ruleForm')" size="mini" v-if="flag4">返回上级</el-button> -->
      </el-form-item>
      <el-form-item label="账号类型" prop="userType">
        <el-select v-model="ruleForm.userType">
          <el-option label="总部" value="1" v-if="flagone"></el-option>
          <el-option label="大区" value="2" v-if="flagtwo"></el-option>
          <el-option
            label="营销区域业务经理"
            value="3"
            v-if="flagthree"
          ></el-option>
          <el-option label="店主" value="4" v-if="flagfour"></el-option>
          <el-option label="店长" value="5" v-if="flagfive"></el-option>
          <el-option label="门店业务员" value="6" v-if="flagsix"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="状态：" prop="status">
        <el-select v-model="ruleForm.status" prop="status" :disabled="disabledFlag">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="状态：" prop="status">
        <el-radio v-model="ruleForm.status" label="1">启用</el-radio>
        <el-radio v-model="ruleForm.status" label="0">禁用</el-radio>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          size="mini"
          v-if="flag3"
          >保 存</el-button
        >
        <!-- <el-button @click="goback()" size="mini" type="primary">返回</el-button> -->
        <el-button
          @click="resetForm('ruleForm')"
          size="mini"
          type="primary"
          v-if="flag3"
          >取 消</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisibleorg" title="请选择组织" width="35%">
      <div>
        <!--
          default-checked-keys  默认勾选的节点的 key 的数组
          setCheckedKeys
          setChecked
        -->
        <el-tree
          v-loading="treeLoading"
          :data="data"
          ref="tree"
          show-checkbox
          node-key="orgSeq"
          :props="defaultProps"
          :default-checked-keys="this.checkedarr"
          @check-change="handleNodeClick"
          @check="handleNodeClickone"
          check-strictly
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleorg = false" size="mini"
          >取 消</el-button
        >
        <el-button type="primary" @click="onSubmit()" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addcount, changecount, queryUserById } from '@/api/platformmanage';
import { getmemberorg } from '@/api/organaz';
import md5 from 'js-md5';
export default {
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'orgName',
      },
      //   orgList: [],
      //   fenorgSeq: "",

      checkedarr: [],
      arrid: [],
      ruleForm: {
        userId: '',
        dangorgname: [],
        password: '',
        sex: 1,
        userName: '',
        realName: '',
        userType: '',
        email: '',
        status: '',
        tel: '',
        orgSeq: '',
        orgList: [],
      },
      flagone: false,
      flagtwo: false,
      flagthree: false,
      flagfour: false,
      flagfive: false,
      flagsix: false,

      flagmi: true,
      dialogVisibleorg: false,
      logininfoone: {},
      disabledFlag: false,
      flag4: true,
      flag3: true,
      userId: '',
      restwo: [],
      rules: {
        userId: [{ required: true, message: '请输入账号', trigger: 'blur' }],

        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'blur' },

        //   {
        //     pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
        //     message: '请输入正确的邮箱格式',
        //     trigger: 'blur',
        //   },
        // ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          //   {
          //     pattern: /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{8,20}$/,

          //     message:
          //       "新密码必须为8-20位字符，并且包含数字大小写字母和特殊字符。",
          //     trigger: "blur"
          //   }
        ],
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[0123456789])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur',
          },
        ],
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择男女', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        userType: [
          { required: true, message: '请输入账号类型', trigger: 'change' },
        ],
        dangorgname: [
          { required: true, message: '请选择当前组织', trigger: 'change' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
        ],
        // password: [{ required: true }]
      },
      treeLoading: false
    };
  },
  mounted() {
    if (this.$route.params.flagmi == false) {
      (this.flagone = true),
        (this.flagtwo = true),
        (this.flagthree = true),
        (this.flagfour = true),
        (this.flagfive = true),
        (this.flagsix = true);
    }
    var v = this.$route.params.edit;
    console.log(v, 'uu');
    this.flag3 = this.$route.params.flag3;
    if (this.$route.params.flag3 === false) {
      this.logininfo = localStorage.getItem('logininfo');
      this.userId = JSON.parse(this.logininfo).userId;
      this._queryUserById();
    }
    if (this.$route.params.flag4 === false) {
      this.logininfoone = localStorage.getItem('logininfo');
      this.logininfoone = JSON.parse(this.logininfoone);
      this.ruleForm.userName = this.logininfoone.userName;
      this.ruleForm.sex = this.logininfoone.sex;
      this.ruleForm.realName = this.logininfoone.realName;
      this.ruleForm.email = this.logininfoone.email;
      this.ruleForm.tel = this.logininfoone.tel;
      this.ruleForm.status = String(this.logininfoone.status);
      this.ruleForm.dangorgname = this.logininfoone.dangorgname;
      this.disabledFlag = true;
      this.ruleForm.orgSeq = this.logininfoone.orgSeq;
    }
    if (v) {
      this.ruleForm.userId = v.userId;
      this.ruleForm.password = v.password;
      this.ruleForm.userName = v.userName;
      this.ruleForm.sex = v.sex;
      this.ruleForm.realName = v.realName;
      this.ruleForm.email = v.email;
      this.ruleForm.tel = v.tel;
      this.ruleForm.orgSeq = v.orgSeq;
      this.ruleForm.userType = String(v.userType);
      this.ruleForm.tenantId = v.tenantId;
      this.ruleForm.status = String(v.status);
      // this.ruleForm.dangorgname = v.orgList[0].orgName;
      v.orgList.forEach((item) => {
        this.ruleForm.dangorgname.push(item.orgName);
        this.checkedarr.push(item.orgSeq);
        this.ruleForm.orgList.push({ orgSeq: item.orgSeq });
      });
      console.log(this.ruleForm.orgList, '777');
      //   this.ruleForm.orgList = v.orgList;
    } else {
      this.ruleForm.status = '1';
    }
  },
  methods: {
    goback() {
      this.$router.go('-1');
    },
    handleNodeClickone(data, checked, node) {
      console.log(data.orgName, data, '333');
      if (data.level >= 4) {
        this.$message.error('不可添加门店账号');
        return;
      }
      if (data.level == 1) {
        this.flagone = true;
        this.flagtwo = false;
        this.flagthree = false;
        this.flagfour = false;
        this.flagfive = false;
        this.flagsix = false;
      } else if (data.level == 2) {
        this.flagone = false;
        this.flagtwo = true;
        this.flagthree = false;
        this.flagfour = false;
        this.flagfive = false;
        this.flagsix = false;
      } else if (data.level == 3) {
        this.flagone = false;
        this.flagtwo = false;
        this.flagthree = true;
        this.flagfour = false;
        this.flagfive = false;
        this.flagsix = false;
      } else {
        this.flagone = false;
        this.flagtwo = false;
        this.flagthree = false;
        this.flagfour = true;
        this.flagfive = true;
        this.flagsix = true;
      }
      if (this.ruleForm.userType == 4 || this.$route.params.userType == 4) {
        var index = this.ruleForm.dangorgname.indexOf(data.orgName);
        if (index !== -1) {
          this.ruleForm.dangorgname.splice(index, 1);
        } else {
          this.ruleForm.dangorgname.push(data.orgName);
          this.ruleForm.dangorgname = [...new Set(this.ruleForm.dangorgname)];
        }
      } else {
        this.ruleForm.dangorgname = [];
        this.ruleForm.dangorgname.push(data.orgName);
      }

      let res = this.$refs.tree.getCheckedNodes();
      let resone = this.$refs.tree.getCheckedKeys();

      let arr = [];

      console.log(this.ruleForm.dangorgname, 'iiiuuu');
      console.log(resone, 'iii');
      resone.forEach((item, i) => {
        // this.fenorgSeq = item;
        // this.ruleForm.fenorgname = item.orgName;

        this.ruleForm.orgList = [];
        // this.ruleForm.orgList = [{ orgSeq: item }];
        this.ruleForm.orgList.push({ orgSeq: item });
        // this.ruleForm.orgList = this.unique(this.ruleForm.orgList);
        console.log(this.ruleForm.orgList, 'opop222');
      });
    },
    handleNodeClick(data, checked, node) {
      //   console.log(data, "777");

      //   console.log(data.orgName, "opoprrrr");
      if (this.ruleForm.userType == 4 || this.$route.params.userType == 4) {
        let res = this.$refs.tree.getCheckedNodes();
        this.restwo = this.$refs.tree.getCheckedKeys();

        // let arr = [];
        // console.log(resone, "op111");
        // resone.forEach((item, i) => {
        //   this.fenorgSeq = item;
        //   this.ruleForm.fenorgname = item.orgName;

        //   this.ruleForm.orgList = [{ orgSeq: item }];
        //   console.log(this.ruleForm.orgList, "opop222");
        // });
      } else {
        this.restwo = this.$refs.tree.getCheckedKeys();

        if (checked === true) {
          this.checkedId = data.orgSeq;
          this.$refs.tree.setCheckedKeys([data.orgSeq]);
        } else {
          if (this.checkedId == data.orgSeq) {
            this.$refs.tree.setCheckedKeys([data.orgSeq]);
          }
        }
      }
    },
    onSubmit() {
      this.dialogVisibleorg = !this.dialogVisibleorg;
      console.log(this.restwo, 'ooo');
      this.checkedarr = this.restwo;
      this.restwo.forEach((item) => {
        this.ruleForm.orgList.push({ orgSeq: item });
        this.ruleForm.orgList = this.unique(this.ruleForm.orgList);
        // this.ruleForm.orgList = [...new Set(this.ruleForm.orgList)];
        console.log(this.ruleForm.orgList, '888');
      });
      console.log(this.ruleForm.dangorgname, '999');
    },
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.orgSeq) && res.set(arr.orgSeq));
    },
    selectorg() {
      this.flagone = false;
      this.flagtwo = false;
      this.flagthree = false;
      this.flagfour = false;
      this.flagfive = false;
      this.flagsix = false;
      this.dialogVisibleorg = !this.dialogVisibleorg;
      let data = {
        // size: this.listQuery.size,
        // current: this.listQuery.current,
        // condition: {}
      };
      this.treeLoading = true;
      getmemberorg(data).then((res) => {
        // res.records.forEach((item, i) => {
        //   this.options.push({ value: item.orgSeq, label: item.orgName });
        // });

        this.loading = false;
        this.total = res.total;
        this.data = res.records;
      }).finally(() => {
        this.treeLoading = false;
      });
    },
    _queryUserById() {
      let data = {
        userId: this.userId,
      };
      queryUserById(data).then((res) => {
        this.ruleForm.userId = res.result.userId;
        this.ruleForm.password = res.result.password;
        this.ruleForm.userName = res.result.userName;
        this.ruleForm.sex = res.result.sex;
        this.ruleForm.realName = res.result.realName;
        this.ruleForm.email = res.result.email;
        this.ruleForm.tel = res.result.tel;
        this.ruleForm.orgSeq = res.result.orgSeq;
        this.ruleForm.userType = String(res.result.userType);
        this.ruleForm.tenantId = res.result.tenantId;
        this.ruleForm.status = String(res.result.status);
      });
    },
    handleCheckChange() {
      let res = this.$refs.tree.getCheckedNodes();
      let arr = [];
      res.forEach((item) => {
        arr.push(item.orgSeq);
        this.arrid.push(item.orgSeq);
        this.arrone = arr;
      });
    },
    submitForm(formName) {
      if (this.$route.params.edit) {
        // if (this.ruleForm.userName == "" || this.ruleForm.userName == null) {
        //   this.$message.error("请输入账号");
        //   return;
        // }

        // if (this.ruleForm.realName == "" || this.ruleForm.realName == null) {
        //   this.$message.error("请输入姓名");
        //   return;
        // }
        // if (this.ruleForm.sex == "" || this.ruleForm.sex == null) {
        //   this.$message.error("请选择性别");
        //   return;
        // }
        // if (this.ruleForm.password == "" || this.ruleForm.password == null) {
        //   this.$message.error("请输入密码");
        //   return;
        // }
        // if (this.ruleForm.email == "" || this.ruleForm.email == null) {
        //   this.$message.error("请输入邮箱");
        //   return;
        // }
        // if (this.ruleForm.tel == "" || this.ruleForm.tel == null) {
        //   this.$message.error("请输入手机号");
        //   return;
        // }
        // if (
        //   this.ruleForm.dangorgname == "" ||
        //   this.ruleForm.dangorgname == null
        // ) {
        //   this.$message.error("请选择组织");
        //   return;
        // }

        // if (this.ruleForm.userType == "" || this.ruleForm.userType == null) {
        //   this.$message.error("请输入选择账号类型");
        //   return;
        // }

        // if (this.ruleForm.status == "" || this.ruleForm.status == null) {
        //   this.$message.error("请选择状态");
        //   return;
        // }

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.ruleForm.orgSeq = this.$route.params.edit.orgList.length > 0 ? this.$route.params.edit.orgList[0].orgSeq : "";
            
            changecount(this.ruleForm).then((res) => {
              if (res.code == 0) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                this.$router.push('accountList');
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });

        // changecount(this.ruleForm).then(res => {
        //   if (res.code == 0) {
        //     this.$message({
        //       showClose: true,
        //       message: res.message,
        //       type: "error"
        //     });
        //   } else {
        //     this.$message({
        //       showClose: true,
        //       message: res.message,
        //       type: "success"
        //     });
        //     this.$router.push("accountList");
        //   }
        // });
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // this.ruleForm.orgSeq = this.$route.params.edit.orgList.length > 0 ? this.$route.params.edit.orgList[0].orgSeq : "";
            addcount(this.ruleForm).then((res) => {
              if (res.code == 0) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                this.$router.push('accountList');
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
        // if (this.ruleForm.userName == "" || this.ruleForm.userName == null) {
        //   this.$message.error("请输入账号");
        //   return;
        // }

        // if (this.ruleForm.realName == "" || this.ruleForm.realName == null) {
        //   this.$message.error("请输入姓名");
        //   return;
        // }
        // if (this.ruleForm.sex == "" || this.ruleForm.sex == null) {
        //   this.$message.error("请选择性别");
        //   return;
        // }
        // if (this.ruleForm.password == "" || this.ruleForm.password == null) {
        //   this.$message.error("请输入密码");
        //   return;
        // }
        // if (this.ruleForm.email == "" || this.ruleForm.email == null) {
        //   this.$message.error("请输入邮箱");
        //   return;
        // }
        // if (this.ruleForm.tel == "" || this.ruleForm.tel == null) {
        //   this.$message.error("请输入手机号");
        //   return;
        // }
        // if (
        //   this.ruleForm.dangorgname == "" ||
        //   this.ruleForm.dangorgname == null
        // ) {
        //   this.$message.error("请选择组织");
        //   return;
        // }

        // if (this.ruleForm.userType == "" || this.ruleForm.userType == null) {
        //   this.$message.error("请输入选择账号类型");
        //   return;
        // }

        // if (this.ruleForm.status == "" || this.ruleForm.status == null) {
        //   this.$message.error("请选择状态");
        //   return;
        // }

        // this.ruleForm.orgSeq = this.fenorgSeq;
        //     addcount(this.ruleForm).then(res => {
        //       if (res.code == 0) {
        //         this.$message({
        //           showClose: true,
        //           message: res.message,
        //           type: "error"
        //         });
        //       } else {
        //         this.$message({
        //           showClose: true,
        //           message: res.message,
        //           type: "success"
        //         });
        //         this.$router.push("accountList");
        //       }
        //     });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push('accountList');
    },
  },
};
</script>

<style lang="less" scoped>
.adminSet {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  padding: 50px 0px 20px 150px;
  width: 52%;
  position: relative;
}
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}
.el-input {
  width: 60%;
}
</style>
